<span class="help-block">提示: 自提订单只可在批量打印中打印发货单，数据量大可造成页面卡顿，为保证稳定性单次打印的订单不要超过20张(可根据下单时间分批次打印)。</span>
<div class="panel panel-default">
	<div class="panel-heading">订单信息
		<span class="pull-right">
			<span style="cursor: pointer;" id="fold" data-state="0"><i class="fa fa-arrow-circle-up"></i> 全部收起</span>
		</span>
	</div>
	<div id="result-order" style="padding: 5px;" class="panel-body">
		{if count($orders)>0}
			<table class="table table-responsive" style="table-layout: fixed;  margin-bottom: 0px;">
					<tr style="background:#f8f8f8">
						<td style="width: 26px; padding-left: 6px;">
							<label class="checkboxinline"><input type="checkbox" value="1" class="checkAll" checked="checked"></label>
						</td>
						<td style="width:75px;border-left:1px solid #f2f2f2;">商品</td>
						<td ></td>
						<td style="width:75px;text-align: right;;">单价/数量</td>
						<td style="width:75px;text-align: center;">支付/配送</td>
						<td style="width:110px;text-align: center;">价格</td>
						<td style="width:85px;text-align: center;">下单时间</td>
						<td style="width:70px;text-align: center">状态</td>
						<td style="width:80px;text-align: center">打印状态</td>
					</tr>
			</table>
			
			{loop $orders $item} 
				<table class="table table-responsive table-order" style="table-layout: fixed; border-bottom: 1px solid #f2f2f2;  margin-bottom: 0px;" data-ordersn="{$item['ordersn']}">
					<tr style="height: 0;">
						<th style="width: 26px;"></th>
						<th style="width: 75px;"></th>
						<th></th>
						<th style="width: 75px;"></th>
						<th style="width: 75px;"></th>
						<th style="width: 110px;"></th>
						<th style="width: 85px;"></th>
						<th style="width: 70px;"></th>
						<th style="width: 80px;"></th>
					</tr>
					
					<tr class="trorder">
						<td style="width: 26px; padding-left: 6px;">
							<label class="checkboxinline"><input type="checkbox" value="1" class="checkOrder" checked="checked"></label>
						</td>
						<td colspan="4">
							订单编号: {$item['ordersn']}
							{if !empty($item['refundstate'])}<label class='label label-danger'>退款申请</label>{/if}
							{if $item['dispatchtype']==1}<label class='label label-primary'>用户自提</label>{/if} 
							{if $item['status']==2}
								快递公司: {if empty($item['expresscom'])}其他快递{else}{$item['expresscom']}{/if} 快递单号: {$item['expresssn']}
							{/if}
						</td>
						<td class="aops" style="text-align:right;font-size:12px;" colspan="4">
							<a class="op" href="{php echo webUrl('order/detail', array('id'=>$item['id']))}" style="margin: 0; padding: 0px 5px;" target="_blank">查看详情</a>
							<a class="op order-print-state-express" href="javascript:;">
								{if $item['printstate']==0}快递单未打印{elseif $item['printstate']==1}快递单部分打印{elseif $item['printstate']==2}快递单打印完成{/if}
							</a>
							<a class="op order-print-state-invoice" href="javascript:;">
								{if $item['printstate2']==0}发货单未打印{elseif $item['printstate2']==1}发货单部分打印{elseif $item['printstate2']==2}发货单打印完成{/if}
							</a>
							<a class="op fold" href="javascript:;" data-state="0">收起</a>
						</td>
					</tr>
					
			{loop $item['goods'] $k $g}
				<!-- 此处记录数据 -->
				<tr class="trbody trfold print-data" 
					data-send-status="{$item['send_status']}" 
					data-print-goodid="{$g['id']}" 
					data-print-total="{$g['total']}" 
					data-print-title="{$g['title']}" 
					data-print-option="{$g['optiontitle']}" 
					data-print-orderid="{$item['id']}" 
					data-print-ordersn="{$item['ordersn']}" 
					data-print-goodssn="{$g['goodssn']}" 
					data-print-productsn="{$g['productsn']}" 
					data-print-marketprice="{php echo $g['realprice']/$g['total']}"
					data-print-productprice="{php echo $g['price']/$g['total']}" 
					data-print-realprice="{php echo $g['realprice']/$g['total']}" 
					data-print-unit="{$g['unit']}" 
					data-print-weight="{$g['weight']}"
					>
					<td style="width: 26px; padding-left: 6px;">
						<label class="checkboxinline"><input type="checkbox" value="1" class="checkGood" checked="checked"></label>
					</td>
					<td style="overflow:hidden;">
						<img style="width:50px;height:50px;border:1px solid #ccc; padding:1px;" src="{php echo tomedia($g['thumb'])}" onerror="this.src='./resource/images/nopic.jpg'; this.title='图片未找到.'" />
					</td>
					<td style="text-align: left;overflow:hidden;">
						<span class="print-short" data-print-short="{$g['shorttitle']}" data-toggle='ajaxEdit' data-href="{php echo webUrl('exhelper/short/edit',array('id'=>$g['id']))}">
							{if empty($g['shorttitle'])}
								{$g['title']}
							{else}
								{$g['shorttitle']}
							{/if}
						</span>
						
						{if !empty($g['optiontitle'])}<br/>{$g['optiontitle']}{/if}
						{if !empty($g['goodssn'])}<br/>{$g['goodssn']}{/if}
					</td>
					<td style="text-align: right;">
						{php echo number_format($g['realprice']/$g['total'],2)}<br>
						x{$g['total']}
					</td>
					{if $k==0}
						<td style="text-align:center;" rowspan="{php echo count($item['goods'])}">
							<label class='label label-{$item['css']}'>{$item['paytype']}</label>
							<br>
							<span style="margin-top:5px;display:block;">{$item['dispatchname']}</span>
						</td>
						<td style="text-align:center" rowspan="{php echo count($item['goods'])}">￥{$item['price']} 
							{if $item['dispatchprice']>0}
							<br/>(含运费:￥{php echo number_format( $item['dispatchprice'],2)})
							{/if}
						</td>
						<td style="text-align:center" rowspan="{php echo count($item['goods'])}">
							{php echo date('Y-m-d', $item['createtime'])} <br>{php echo date('H:i:s', $item['createtime'])} 
						</td>
						<td style="line-height:20px;text-align:center" class="ops" rowspan="{php echo count($item['goods'])}">
							<label class='label label-{$item['statuscss']} label-oss'>{$item['statusname']}</label>
						</td>
					{/if}
					<td style="line-height:20px;text-align:center" class="ops">
						<label class='label label-default print-state-express' data-state="{$g['printstate']}">快递单x{$g['printstate']}</label><br>
						<label class='label label-default print-state-invoice' data-state="{$g['printstate2']}">发货单x{$g['printstate2']}</label>
					</td>
				</tr>
			{/loop}
				<tr class="trfold">
					<td class="address" colspan="9" style="text-align: right;">
						{if $item['dispatchtype']==0}
							收件人: 
							<span class="print-data-realname" data-value="{$item['address']['realname']}">{$item['address']['realname']}</span>
							(<span class="print-data-nickname" data-value="{$item['address']['nickname']}">{$item['address']['nickname']}</span>) /
							<span class="print-data-mobile" data-value="{$item['address']['mobile']}">{$item['address']['mobile']}</span>
							收货地址: 
							<span class="print-data-province" data-value="{$item['address']['province']}">{$item['address']['province']}</span>
							<span class="print-data-city" data-value="{$item['address']['city']}">{$item['address']['city']}</span>
							<span class="print-data-area" data-value="{$item['address']['area']}">{$item['address']['area']}</span>
							<span class="print-data-address" data-value="{$item['address']['address']}">{$item['address']['address']}</span>
							<a href="javascript:;" class="print-edit-btn" data-state="e">编辑</a>
						{elseif $item['dispatchtype']==1}
							提货人: 
							<span class="print-data-realname" data-value="{$item['address']['realname']}">{$item['address']['realname']}</span>
							(<span class="print-data-nickname" data-value="{$item['address']['nickname']}">{$item['address']['nickname']}</span>) /
							<span class="print-data-mobile" data-value="{$item['address']['mobile']}">{$item['address']['mobile']}</span>
							提货地址:
							<span class="print-data-province" data-value=""></span>
							<span class="print-data-city" data-value=""></span>
							<span class="print-data-area" data-value=""></span>
							<span class="print-data-address" data-value="{$item['address']['address']}">{$item['address']['address']}</span>
						{/if}
					</td>
				</tr>
				
				<tr style=";border-bottom:none;background:#fafafa;" class="trfold">
					<td colspan="9" style="text-align:left"><i class="fa fa-cubes"></i> 发货信息</td>
				</tr>
				<tr class="trfold">
					<td style="height:auto; padding: 0; border: 0;" colspan="9">
						<textarea style="max-width: 100%; min-width: 100%;" class="form-control richtext valid sendinfo"></textarea>
					</td>
				</tr>
				<tr class="trfold">
					<td colspan="5" style="color: #F27474; text-align: left;">买家备注: <span class="remark1">{if !empty($item['remark'])}{$item['remark']}{else}无{/if}</span></td>
					<td colspan="4" style="color:#F0C49B; text-align: right;">卖家备注: <span class="remark2">{if !empty($item['remarksaler'])}{$item['remarksaler']}{else}无{/if}</span></td>
				</tr>
				</table>
			{/loop}
			
		{else}
			<p style="text-align: center; line-height: 100px;">抱歉！未查到相关数据。 </p>
		{/if}
	</div>
</div>


		<div class="print-btn">
			{ifp 'exhelper.print.batch.express'}
				<a href="javascript:;" class="btn btn-success btn-sm" id="print-express" data-ban = "0" data-cate="1">打印快递单</a>
			{/if}
			{ifp 'exhelper.print.batch.invoice'}
				<a href="javascript:;" class="btn btn-warning btn-sm" id="print-invoice" data-ban = "0" data-cate="2">打印发货单</a>
			{/if}
			{ifp 'exhelper.print.batch.dosend'}
				<a href="javascript:;" class="btn btn-primary btn-sm" id="print-send" data-ban = "0">一键发货</a>
			{/if}
			{ifp 'exhelper.print.batch.express|exhelper.print.batch.invoice|exhelper.print.batch.dosend'}
				<a class="btn btn-default btn-sm" id="print-template" data-ban = "0" onclick='$("#chooseTemp").modal();'>选择打印模板</a>
			{/if}
		</div>
{template 'exhelper/print/print_tpl_template'} 
<script>

	$(function(){
		
		// 计算发货信息
		changeSendInfo(); 

		
		$("#print-express, #print-invoice").click(function(){
			
			if(!isCLodop){
				alert(LodopTip);
				return;
			}
			
			saveUser();
			
			var LODOP=getCLodop();
			
			var _thisBan = $(this).data("ban");
			if(_thisBan>0){
				return;
			}
			var _thisCate = $(this).data("cate");
			// 获取打印模板
			var printUserId = temp_sender = $("#temp_sender option:selected").val();
			var temp_express = $("#temp_express option:selected").val();
			var temp_invoice = $("#temp_invoice option:selected").val();
			// 判断 打印快递单 or 打印发货单
			if(_thisCate==1){
				var printTempId = temp_express;
			}
			if(_thisCate==2){
				var printTempId = temp_invoice;
			}
			if(printTempId==''){
				alert("请先选择打印模版");
				return;
			}
			if(temp_sender==''){
				alert("请先选择发件人信息模版");
				return;
			}
			// ajax获得打印模版 x3
			$.ajax({
				type: 'POST', 
				url: "{php echo webUrl('exhelper/print/single/getprintTemp')}",
				data: {type:_thisCate,printTempId:printTempId,printUserId:printUserId},
				dataType:'json',
				async:false,
				success: function(d){                        	
					if(d.result=="success"){
						printDatas = d.respDatas;
						printUser = d.respUser;
						printTemp = d.respTemp;
					}else{
						alert(d.resp);
						return;
					}
				}
			});
			
			// 定义打印订单信息
			var printArr = [];
			$("#result-order").find(".table-order").each(function(){
				var _this = $(this).find("input[type=checkbox]:checked").not(".checkOrder");
				if(_this.length>0){
					printArr.push({
						'ordersn':$(this).data("ordersn"), 
						'sendInfo':$(this).find(".sendinfo").val(),
						'realName':$(this).find(".print-data-realname").data("value"),
						'nickName':$(this).find(".print-data-nickname").data("value"),
						'mobile':$(this).find(".print-data-mobile").data("value"),
						'province':$(this).find(".print-data-province").data("value"),
						'city':$(this).find(".print-data-city").data("value"),
						'area':$(this).find(".print-data-area").data("value"),
						'address':$(this).find(".print-data-address").data("value"),
						'expremark1':$.trim($(this).find(".remark1").text()),
						'expremark2':$.trim($(this).find(".remark2").text())
					});
				}
			});
			
			// 定义打印模版信息
		 	LODOP.PRINT_INITA(0,0,printTemp.width+"mm",printTemp.height+"mm","单据打印");
			if(printTemp.bg){
				LODOP.ADD_PRINT_SETUP_BKIMG("<img border='0' src='"+printTemp.bg+"'>");
				LODOP.SET_SHOW_MODE("BKIMG_IN_PREVIEW",1); 
			}
			LODOP.SET_PRINT_MODE("AUTO_CLOSE_PREWINDOW",true);
			
			// 执行遍历并替换数据
			$.each(printArr,function(ii,dd){
				printDatasT = jQuery.extend(true, {}, printDatas); 
				$.each(printDatasT,function(){
					this.items = this.items.replace("ordersn",dd.ordersn);
					this.items = this.items.replace("sendinfo",dd.sendInfo);
					this.items = this.items.replace("realname",dd.realName);
					this.items = this.items.replace("nickname",dd.nickName);
					this.items = this.items.replace("mobile",dd.mobile);
					this.items = this.items.replace("province",dd.province);
					this.items = this.items.replace("city",dd.city);
					this.items = this.items.replace("area",dd.area);
					this.items = this.items.replace("address",dd.address);
					this.items = this.items.replace("shopname",printTemp.shopname);
					this.items = this.items.replace("expremark1",dd.expremark1);
					this.items = this.items.replace("expremark2",dd.expremark2);
				});
				// 遍历
				$.each(printDatasT,function(i,d){
					if(d.cate==1){
						LODOP.ADD_PRINT_TEXTA('"t_'+i+'"',d.top+"px",d.left+"px",d.width+"px",d.height+"px",d.pre+d.items+d.last);
						if(d.color){
							LODOP.SET_PRINT_STYLEA('"t_'+i+'"',"FontColor",d.color);	// 文字颜色
						}
						if(d.bold){
							LODOP.SET_PRINT_STYLEA('"t_'+i+'"',"Bold",1);	// 文字加粗
						}
						if(d.align){
							LODOP.SET_PRINT_STYLEA('"t_'+i+'"',"Alignment",d.align);	// 对齐方式
						}
						var FontSize = !d.size?"12":d.size;
						LODOP.SET_PRINT_STYLEA('"t_'+i+'"',"FontSize",FontSize);	//文字大小
						var FontName = !d.font?"微软雅黑":d.font;
						LODOP.SET_PRINT_STYLEA('"t_'+i+'"',"FontName",FontName);	// 文字字体
					}
					if(d.cate==2){
					var strings = d.string.split(',');
					var values = d.items.split(',');
					var _html = '<table style="width: '+d.width+'; display:table-fixed; border-collapse:collapse;border-spacing:0;border-left:1px solid '+d.color+';border-top:1px solid '+d.color+'; corlor:'+d.color+'; ';
							if(d.align==1){
								_html += "text-align:left;"
							}
							if(d.align==2){
								_html += "text-align:center;"
							}
							if(d.align==3){
								_html += "text-align:right;"
							}
							_html += '">';
							
						  _html += '<tr>';
						  $.each(strings, function(ii,s) {
						  	_html += '<td style="border-right:1px solid '+d.color+'; border-bottom:1px solid '+d.color+'; font-size:'+d.size+'pt; font-family:'+d.font+'; color:'+d.color+';">'+s;
						  	_html += '</td>';
						  });
						  _html += '</tr>';
						  
						  var all_total = 0;
						  var all_productprice = 0;
						  var all_marketprice = 0;
						  var all_realprice = 0;
						  var all_allprice = 0;
						  
						  var info = [];
						  
						  $("table[data-ordersn='"+dd.ordersn+"']").find("input:checkbox:checked").not(".checkOrder").each(function(index){ 
						  	var _this = $(this).closest(".print-data");
						  	var _ordersn = _this.data("print-ordersn")	// 订单编号
						  	var _goodname = _this.data("print-title");	// 商品名称						  	
						  	var _goodshortname = _this.find(".print-short").data("print-short");	// 商品简称
						  	var _goodssn = _this.data("print-goodssn");	// 商品编码
						  	var _productsn = _this.data("print-productsn");	//商品条码
						  	var _marketprice = _this.data("print-marketprice");	//商品原价
						  	var _productprice = _this.data("print-productprice");	//商品现价
						  	var _allprice = _this.data("print-realprice") * _this.data("print-total");	// 商品总价
						  	var _total = _this.data("print-total");	// 商品数量
						  	var _note = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';	//备注栏
						  	var _goodoption = _this.data("print-option");	// 商品规格 
						  	var _goodunit = _this.data("print-unit");	// 商品单位
						  	var _goodweight = _this.data("print-weight");	// 商品重量
						  	var _realprice = _this.data("print-realprice");	// 商品折后价格
						  	
						  	var _orderremark1 = _this.closest(".table-order").find(".remark1").text();	// 订单备注
						  	var _orderremark2 = _this.closest(".table-order").find(".remark2").text();	// 订单备注
						  	
						  	info.push({
						  		'odsn': _ordersn,
						  		'goodname': _goodname,
						  		'goodshortname': _goodshortname,
						  		'goodssn': _goodssn,
						  		'productsn': _productsn,
						  		'marketprice': _marketprice,
						  		'productprice': _productprice,
						  		'allprice': _allprice,
						  		'total': _total,
						  		'note': _note,
						  		'goodoption': _goodoption,
						  		'goodunit': _goodunit,
						  		'goodweight': _goodweight,
						  		'realprice': _realprice,
						  		'orderremark1':_orderremark1,
						  		'orderremark2':_orderremark2
						  	});
						  	_html += '<tr>';
						  	
						  	$.each(values, function(iii,val) {
						  		_html += '<td style="border-right:1px solid '+d.color+'; border-bottom:1px solid '+d.color+'; font-size:'+d.size+'pt; font-family:'+d.font+'; color:'+d.color+';">';
						  		if(val=="printsn"){
						  			_html += index+1;
						  		}else{
						  			_html += info[index][val];
						  			if(val=='total'){all_total += (info[index][val]);}
						  			if(val=='productprice'){all_productprice += (info[index][val]);}
						  			if(val=='marketprice'){all_marketprice += (info[index][val]);}
						  			if(val=='realprice'){all_realprice += (info[index][val]);}
						  			if(val=='allprice'){all_allprice += (info[index][val]);}
						  		}
						  		_html += '</td>';
						  	});
						  	_html += '</tr>';
						  });
						  _html += '<tr>';
						  	$.each(values, function(iii,val) {
						  		_html += '<td style="border-right:1px solid '+d.color+'; border-bottom:1px solid '+d.color+'; font-size:'+d.size+'pt; font-family:'+d.font+'; color:'+d.color+';">';
						  		if(val=='total'){_html += "总计:"+all_total}
						  		if(val=='productprice'){_html += "总计:"+parseFloat(all_productprice).toFixed(2)}
						  		if(val=='marketprice'){_html += "总计:"+parseFloat(all_marketprice).toFixed(2)}
						  		if(val=='realprice'){_html += "总计:"+parseFloat(all_realprice).toFixed(2)}
						  		if(val=='allprice'){_html += "总计:"+parseFloat(all_allprice).toFixed(2)}
						  		_html += '</td>';
						  	});
						  _html += '</tr>';
						  _html += '</table>';
						LODOP.ADD_PRINT_HTM(d.top+"px", d.left+"px", "100%", "100%", _html);
				}
				});
				LODOP.NewPage();
	        });
			
			
			
			// 提交打印
			// 获取打印状态
			if (LODOP.CVERSION) {
			        LODOP.On_Return=function(TaskID,Value){
			             if (Value==1){
			             	tip.msgbox.suc("已提交至打印机");
			             	// 执行修改订单表数据
			             	changeOrderPrintInfo(_thisCate);
			             }else{
			             	tip.msgbox.err("打印已取消");
			             }
			        };
			        LODOP.PREVIEW();
			        return;
			};
			
		});
		
		// 执行一键发货
		$("#print-send").click(function(){
			var thisState = $(this).data("state");
			if(thisState>0){
				return;
			}
			// 执行保存收件人信息
			saveUser(); 
			var temp_express = $("#temp_express option:selected").val();
			if(temp_express==''){
				tip.msgbox.err("请先选择发货单模板");
				return;
			}
			var orderids = [];
			$("#result-order").find("input:checkbox:checked").not(".checkAll").not(".checkOrder").each(function() {
				var _this = $(this).closest(".print-data");
				var orderid = _this.data("print-orderid");
				var status = _this.data("send-status");
				if(status==1){
					var inarray = $.inArray(orderid,orderids);
					if(inarray<0){
						orderids.push(orderid);
					}
				}
			});
			if(orderids==''){
				tip.msgbox.err("可发货状态订单为空");
				return;
			}

			$.ajax({
				type: 'POST', 
				url: "{php echo webUrl('exhelper/print/batch/getorderinfo')}",
				data: {orderids:orderids,temp_express:temp_express},
				success: function(result){           
					$("#modal-send").find("#main").html(result);
					$("#modal-send").modal({backdrop: 'static', keyboard: false});
				}
			});

		});
		
		// 修改 商品简称 回调方法
		$("[data-toggle='ajaxEdit']").bind('valueChange',function(event,val,oldval){
			$(".print-short").each(function(){
				var st= $(this).data("print-short");
				if(st==oldval){
					$(this).data("print-short",val).html(val);
				}
			});
		});

		
		// 全选按钮
		$(".checkAll").click(function(){
			var _thisState = $(this).is(":checked");
			if(_thisState){
				$("input[type=checkbox]").prop("checked", true);
			}else{
				$("input[type=checkbox]").prop("checked", false);
			}
		});
		// 订单全选按钮
		$(".checkOrder").click(function(){
			var _thisState = $(this).is(":checked");
			if(_thisState){
				$(this).closest(".table").find("input[type=checkbox]").prop("checked", true);
				// 执行遍历全选
				var dd = true;
				$("input[type=checkbox]").not(".checkAll").each(function(){
					_tS = $(this).is(":checked");
					if(!_tS){dd = false;return;} 
				});
				if(dd){
					$(".checkAll").prop("checked", true);
				}
			}else{
				$(this).closest(".table").find("input[type=checkbox]").prop("checked", false);
				$(".checkAll").prop("checked", false);
			}
		});
		// 选择商品按钮
		$(".checkGood").click(function(){
			var _thisState = $(this).is(":checked");
			if(_thisState){
				$(this).prop("checked", true);
				var d = true;
				var dd = true;
				$(this).closest(".table").find(".checkGood").each(function(){
					_tS = $(this).is(":checked");
					if(!_tS){d = false;return;} 
				});
				if(d){
					$(this).closest(".table").find(".checkOrder").prop("checked", true);
				}
				
				$("input[type=checkbox]").not(".checkAll").each(function(){
					_tS = $(this).is(":checked");
					if(!_tS){dd = false;return;} 
				});
				if(dd){
					$(".checkAll").prop("checked", true);
				}
				
			}else{
				$(this).prop("checked", false);
				$(this).closest(".table").find(".checkOrder").prop("checked", false);
				$(".checkAll").prop("checked", false);
			}
		});
		$("#result-order").find("input[type=checkbox]").change(function(){
			var d = false;
			$("input[type=checkbox]").each(function(){
				_tS = $(this).is(":checked");
				if(_tS){d = true;return;} 
			});
			if(d){
				// 可以打印
				$(".print-btn #print-express").removeClass("btn-disabled").addClass("btn-success").data("ban",0);
				$(".print-btn #print-invoice").removeClass("btn-disabled").addClass("btn-warning").data("ban",0);
				$(".print-btn #print-send").removeClass("btn-disabled").addClass("btn-primary").data("ban",0);
			}else{
				// 不可以打印
				$(".print-btn #print-express").removeClass("btn-success").addClass("btn-disabled").data("ban",1);
				$(".print-btn #print-invoice").removeClass("btn-warning").addClass("btn-disabled").data("ban",1);
				$(".print-btn #print-send").removeClass("btn-primary").addClass("btn-disabled").data("ban",1);
			}
			changeSendInfo();
		});
		
		$("#fold").click(function(){
			var state = $(this).data("state");
			if(state==0){
				$(this).html('<i class="fa fa-arrow-circle-down"></i> 全部展开').data("state",1);
				$(".trfold").hide();
				$(".fold").text("展开");
				// 收起
			}
			if(state==1){
				// 折叠
				$(this).html('<i class="fa fa-arrow-circle-up"></i> 全部收起').data("state",0);
				$(".trfold").show();
				$(".fold").text("收起");
			}
		})
		// 单订单折叠
		$(".fold").click(function(){
			var state = $(this).data("state");
			if(state==0){
				$(this).text('展开').data("state",1);
				$(this).closest(".table").find(".trfold").hide();
				// 收起
			}
			if(state==1){
				// 折叠
				$(this).text('收起').data("state",0);
				$(this).closest(".table").find(".trfold").show();
			}
		});
		
		// 编辑收件人信息
		$(".print-edit-btn").click(function(){
			var state = $(this).data("state");
			var _this = $(this).parent();
			var e_realname = _this.find(".print-data-realname");
			var e_nickname = _this.find(".print-data-nickname");
			var e_mobile = _this.find(".print-data-mobile");
			var e_province = _this.find(".print-data-province");
			var e_city = _this.find(".print-data-city");
			var e_area = _this.find(".print-data-area");
			var e_address = _this.find(".print-data-address");
			
			var old_realname = e_realname.data("value");
			var old_mobile = e_mobile.data("value");
			var old_province = e_province.data("value");
			var old_city = e_city.data("value");
			var old_area = e_area.data("value");
			var old_address = e_address.data("value");
			
			if(state=='e'){
				$(this).data("state","s").text("保存");
				e_realname.html("<input type='text' value='"+e_realname.text()+"' style='width:90px;'>");
				e_mobile.html("<input type='text' value='"+e_mobile.text()+"' style='width:95px;'>");
				e_province.html("<input type='text' value='"+e_province.text()+"' style='width:60px;'>");
				e_city.html("<input type='text' value='"+e_city.text()+"' style='width:60px;'>");
				e_area.html("<input type='text' value='"+e_area.text()+"' style='width:60px;'>");
				e_address.html("<input type='text' value='"+e_address.text()+"' style='width:160px;'>");
			}
			else if (state=='s'){
				$(this).data("state","e").text("编辑");
				var val_realname = e_realname.children().val();
				var val_nickname = e_nickname.val()
				var val_mobile = e_mobile.children().val();
				var val_province = e_province.children().val();
				var val_city = e_city.children().val();
				var val_area = e_area.children().val();
				var val_address = e_address.children().val();
				
				var ordersns = [];


					// 全局修改=0 : 只修改单订单收货人信息
					e_realname.html(val_realname).data("value",val_realname);
					e_mobile.html(val_mobile).data("value",val_mobile);
					e_province.html(val_province).data("value",val_province);
					e_city.html(val_city).data("value",val_city);
					e_area.html(val_area).data("value",val_area);
					e_address.html(val_address).data("value",val_address);
					ordersn = $(this).closest(".trfold").prev().data("print-ordersn");
					ordersns.push(ordersn);
				// ajax 执行写入数据库
				$.ajax({
						type: 'POST', 
						url: "{php echo webUrl('exhelper/print/batch/saveuser')}",
						data: {
							realname:val_realname,
							mobile:val_mobile,
							province:val_province,
							city:val_city,
							area:val_area,
							address:val_address,
							ordersns:ordersns
						},
						dataType:'json',
						success: function(result){                        	
							if(result.result=='error'){
								alert(result.resp);
							}
						}
				});
				
			}
			
		});
	});
	
	// 执行发货
	function doSend(){
		var _thisState = $("#dosend").data("state");
		if(_thisState==1){
			tip.msgbox.err("正在执行发货，请稍候。。。");
			return;
		}
		if(_thisState==2){
			return;
		}
		
		var state = 0;
		$(".sendtable").find("input[data-send-state=1]").each(function(){
			if($(this).val()==''){
				tip.msgbox.err("您还有未填写快递单号的订单哦~");
				$(this).focus();
				state = 1;
				return false;
			}
		});
		if(state==0){
			var total =$(".sendtable").find("input[data-send-state=1]").length;
			if(total<1){
				tip.msgbox.err("没有可发货状态的订单");
				return;
			}
			if(confirm('确定执行发货？')){
				$("#dosend").data("state",1).text("正在发货");
				var expresscom = $("#modal-send").find("#expresscom").val();
				var express = $("#modal-send").find("#express").val();
				$(".sendtable").find("input[data-send-state=1]").each(function(i){
					var expresssn = $.trim($(this).val());
					var orderid = $(this).closest("tr").data("orderid");
					$.ajax({
							type: 'POST', 
							url: "{php echo webUrl('exhelper/print/batch/dosend')}",
							data: {orderid:orderid,expresssn:expresssn,expresscom:expresscom,express:express},
							dataType:'json',
							async:false,
							success: function(result){     
								if(result.result=='error'){
									alert(result.resp);
								}
								if(result.result=='success'){
									$("#dosend").text("正在执行...("+i+"/"+total+")");
									$(".sendtable").find(".send-order[data-orderid="+orderid+"]").find("input").attr("disabled","disabled");  
									$(".sendtable").find(".send-order[data-orderid="+orderid+"]").find(".status label").removeClass("label-info").removeClass("label-danger").addClass("label-warning").text("待收货");
									$("#result-order").find(".print-data[data-print-orderid="+orderid+"]").find(".label-oss").removeClass("label-info").removeClass("label-danger").addClass("label-warning").text("待收货");
									$("#result-order").find(".print-data[data-print-orderid="+orderid+"]").data("send-status",0); 
								}
							}
						});
						if(i+1==total){
							tip.msgbox.suc("发货完成");
							$("#dosend").text("发货完成");
							$("#dosend").data("state",2);
						}
				});
			}
		}
		
	}

	
	// 保存时执行 保存收件人信息
	function saveUser(){
		var change = $(".userinfo").data("change");
		if(change!=1){
			return;
		}
		var ordersns = [];
		$("#result-order").find("input[type=checkbox]:checked").not(".checkAll").not(".checkOrder").each(function(){
				var _this = $(this);
				var ordersn = $.trim(_this.closest(".print-data").data("print-ordersn"));
				var inarray = $.inArray(ordersn,ordersns);
				if(inarray<0){
					ordersns.push(ordersn);
				}
		});
		if(!ordersns){
			return;
		}
		var url = "{php echo webUrl('exhelper/print/single/saveuser')}";
		var datas = {
				realname: $.trim($("input[name=realname]").val()),
				nickname: $.trim($("input[name=nickname]").val()),
				mobile: $.trim($("input[name=mobile]").val()),
				province: $.trim($("input[name=province]").val()),
				city: $.trim($("input[name=city]").val()),
				area: $.trim($("input[name=area]").val()),
				address: $.trim($("input[name=address]").val()),
				ordersns: ordersns
			}
		$.post(url, datas, function (result) { });
	}
	
	
	
	
	function changeSendInfo(){
		var _table = $("#result-order").find(".table-order")
		_table.each(function(){
		_this = $(this);
		_this.find(".sendinfo").val("");
		
			var arr = [];
		var sendInfo = '';
			$(this).find("input[type=checkbox]:checked").not(".checkOrder").each(function(){
				var _this = $(this);
				var _tct = _this.closest(".print-data");
				
				var printShort = _tct.find(".print-short").data("print-short");
				var printGid = _tct.data("print-goodid");
				var printTitle = _tct.data("print-title");
				var printTotal = _tct.data("print-total");
				var printOption = _tct.data("print-option");
				var gTitle = !printShort?printTitle:printShort;
				var state = -1;
				$.each(arr,function(i,d){
					if(d.id===printGid && d.option===printOption){
						state = i;
						return false;
					}
				});
				if(state>-1){
					arr[state].num += printTotal;
				}else{
					arr.push({'id':printGid,'title':gTitle,'num':printTotal,'option':printOption});
				} 
			});
			$.each(arr, function(i,v) {
				sendInfo += v.title;
				if(v.option){
					sendInfo += "("+v.option+")";
				}
				sendInfo += " x "+ v.num + "; ";
			});
			_this.find(".sendinfo").val(sendInfo);
		});
	}
	
	function changeOrderPrintInfo(type){
		// 遍历已选中的商品
		var arr = [];
		$("#result-order").find("input[type=checkbox]:checked").not(".checkAll").not(".checkOrder").each(function(){
			var _this = $(this).closest(".print-data");
			var orderid = _this.data("print-orderid");
			var goodid = _this.data("print-goodid");
			arr.push({
				orderid: orderid,
				ordergoodid: goodid
			});
		});
		// 修改订单信息
		$.ajax({
			type: 'POST',
			url: "{php echo webUrl('exhelper/print/batch/changestate')}",
			data: {arr:arr, type:type},
			dataType: 'json',
			success: function(d){
				if(d.result == 'success'){
					$("#result-order").find("input[type=checkbox]:checked").not(".checkAll").not(".checkOrder").each(function(){
						var _this = $(this).closest(".print-data");
						var _table = $(this).closest(".table");
						if(type==1){
							// 快递单打印
							// 修改商品打印状态
							var print_state = _this.find(".print-state-express");
							var print_state_num = print_state.data("state")+1;
							print_state.text("快递单x"+print_state_num).data("state",print_state_num);
							// 修改 订单打印状态
							var _order = _table.find(".order-print-state-express");
							if (d.orderprintstate == 1) {
								_order.text("快递单部分打印");
							} else if (d.orderprintstate == 2) {
								_order.text("快递单打印完成");
							}
						}
						else if(type==2){
							// 发货单打印
							// 修改商品打印状态
							var print_state = _this.find(".print-state-invoice");
							var print_state_num = print_state.data("state")+1;
							print_state.text("发货单x"+print_state_num).data("state",print_state_num);
							// 修改 订单打印状态
							var _order = _table.find(".order-print-state-invoice");
							if (d.orderprintstate == 1) {
								_order.text("发货单部分打印");
							} else if (d.orderprintstate == 2) {
								_order.text("发货单打印完成");
							}
						}
					});
				}else{
					alert(d.resp);
				}
			}
		});
	}
	
	function autonum(){
		var indexval = $(".sendtable").find("input:first");
        var val = $.trim(indexval.val());
        if(val==''){
            indexval.focus();
            return;
        }
        var num =val.replace(/[^0-9]/,'') ;
        var eng = val.replace(num,''); 
        $.ajax({
             url: "{php echo webUrl('util/autonum')}",
             data: {num: num ,len: $(".sendtable").find(":input[data-send-state=1]").length -1},
             type: "POST",
             dataType:"json",
             success: function(arr){
                 for(var i in arr){
                     $(".sendtable").find(":input[data-send-state=1]:eq(" + i + ")").val(eng+ arr[i] );
                 }
             }
         })
    }
	
	
</script>



